package interview.sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 冒泡排序
 * User: xxm
 * Date: 2018-03-27
 * Time: 0:17
 */
public class BubbleSort {

    public static int[] bubbleSort(int[] array) {
        if (array.length == 0) {
            return array;
        }

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                // 若前一个元素大于后一个，将其后置
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        return array;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(
                BubbleSort.bubbleSort(new int[]{0, -1, 2, -5, -20, -10})
        ));

        System.out.println(Arrays.toString(
                BubbleSort.bubbleSort(new int[]{})
        ));

        System.out.println(Arrays.toString(
                BubbleSort.bubbleSort(new int[]{4, 4, 4})
        ));

        System.out.println(Arrays.toString(
                BubbleSort.bubbleSort(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9})
        ));

        System.out.println(Arrays.toString(
                BubbleSort.bubbleSort(new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1})
        ));

        System.out.println(Arrays.toString(
                BubbleSort.bubbleSort(new int[]{31, 50, 12, 44, 2, 55, 78, 43, 24})
        ));
    }
}